import React,{useEffect,useState} from 'react';
import _ from 'lodash';
import {
	Chart,
	Geom,
	Tooltip,
	Coordinate,
	Legend,
	Axis,
	Interaction,
	G2,
	registerShape
} from "bizcharts";
import DataSet from "@antv/data-set";
import { useEffectOnce } from '_react-use@17.2.4@react-use';

// 给point注册一个词云的shape

function getTextAttrs(cfg) {
	return _.assign(
		{},
		cfg.style,
		{
			fontSize: cfg.data.size,
			text: cfg.data.text,
			textAlign: 'center',
			fontFamily: cfg.data.font,
			fill: cfg.color,
			textBaseline: 'Alphabetic'
		}
	);
}
registerShape("point", "cloud", {
	draw(cfg:any, container) {
		const attrs = getTextAttrs(cfg);
		const textShape = container.addShape("text", {
			attrs: _.assign(attrs, {
				x: cfg.x,
				y: cfg.y
			})
		});
		if (cfg.data && cfg.data.rotate) {
			G2.Util.rotate(textShape, cfg.data.rotate * Math.PI / 180);
		}
		return textShape;
	}
});

const d=[ {
  "x": "Papua New Guinea",
  "value": 8151300,
  "category": "australia"
},{
	"x": "India",
	"value": 1316000000,
	"category": "asia"
},]
export default (props)=> {
	let dv = new DataSet.View().source(d);
	let range = dv.range('value');
	let min = range[0];
	let max = range[1];
	dv.transform({
		type: 'tag-cloud',
		fields: ['x', 'value'],
		size: [600, 500],
		font: 'Verdana',
		padding: 0,
		timeInterval: 5000, // max execute time
		rotate() {
			let random = ~~(Math.random() * 4) % 4;
			if (random === 2) {
				random = 0;
			}
			return random * 90; // 0, 90, 270
		},
		fontSize(d) {
			if (d.value) {
				return ((d.value - min) / (max - min)) * (40 - 12) + 12;
			}
			return 0;
		}

	});
	useEffect(()=>{
		if(props.data.length>0){
		dv = new DataSet.View().source(props.data);
		range = dv.range('value');
		min = range[0];
		max = range[1];
		dv.transform({
			type: 'tag-cloud',
			fields: ['x', 'value'],
			size: [600, 500],
			font: 'Verdana',
			padding: 0,
			timeInterval: 5000, // max execute time
			rotate() {
				let random = ~~(Math.random() * 4) % 4;
				if (random === 2) {
					random = 0;
				}
				return random * 90; // 0, 90, 270
			},
			fontSize(d) {
				if (d.value) {
					return ((d.value - min) / (max - min)) * (40 - 12) + 12;
				}
				return 0;
			}

		});
		setDa(dv.rows)
	}
},[props.data])
	const [da,setDa]=useState(dv.rows)
	const scale = {
		x: {
			nice: false
		},
		y: {
			nice: false
		}
	};
	return (
		<Chart
			width={600}
			height={500}
			data={da}
			scale={scale}
			padding={0}
			autoFit={false}
			onPointClick={console.log}
		>
			<Tooltip showTitle={false} />
			<Coordinate reflect="y" />
			<Axis name='x' visible={false} />
			<Axis name='y' visible={false} />
			<Legend visible={false} />
			<Geom
				type='point'
				position="x*y"
				color="category"
				shape="cloud"
				tooltip="value*category"
			/>
			<Interaction type='element-active' />
		</Chart>
	);
}

